<template>
  <div>
    <el-upload
      v-show="false"
      class="avatar-uploader quill-img"
      :show-upload-list="false"
      :on-success="uploadSuccess"
      :http-request="handleUploadForm"
      :before-upload="beforeUpload"
      :format="['jpg', 'jpeg', 'png', 'gif']"
      :max-size="2048"
      multiple
      :action="$config.SERVER_URL + '/file/upload'"
    >
      <!-- <Button icon="ios-cloud-upload-outline" ></Button> -->
    </el-upload>
    <el-card :style="{ height: Number(height) * heightMultiple + 'px' }">
      <quill-editor
        class="quill-editor ql-editor"
        @focus="onEditorFocus($event)"
        @blur="getTxtchild"
        @input="getTxtchild"
        v-model="content"
        :ref="toref"
        :style="{ height: height + 'px' }"
        :options="editorOption"
      >
      </quill-editor>
    </el-card>
  </div>
</template>

<script>
/**
 * 一个页面使用多个富文本编辑器时：（只使用一个的时候可以不传）
 * quillIndex:当前选择上传图片的dom节点的标识，默认是：0
 * toref：区分编辑器的dom节点。
 *disabled: 是否禁止输入  默认false
 *
 */

import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import $config from '@/appConfig.js'
import axios from 'axios'
import Vue from 'vue'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // toggled buttons
  ['blockquote'],
  [
    {
      header: 1
    },
    {
      header: 2
    }
  ], // custom button values
  [
    {
      list: 'ordered'
    },
    {
      list: 'bullet'
    }
  ],
  [
    {
      script: 'sub'
    },
    {
      script: 'super'
    }
  ], // superscript/subscript
  [
    {
      indent: '-1'
    },
    {
      indent: '+1'
    }
  ], // outdent/indent
  [
    {
      direction: 'rtl'
    }
  ], // text direction
  [
    {
      size: ['small', false, 'large', 'huge']
    }
  ], // custom dropdown
  [
    {
      color: []
    },
    {
      background: []
    }
  ], // dropdown with defaults from theme
  [
    {
      header: [1, 2, 3, 4, 5, 6, false]
    }
  ],
  [
    {
      font: []
    }
  ],
  [
    {
      align: []
    }
  ],
  // ["image"],
  ['clean'] // remove formatting button
]
export default {
  name: 'FuncFormsEdit',
  props: {
    heightMultiple: {
      type: Number,
      default: 1.5
    },
    height: {
      type: String,
      default: '200'
    },
    uploadUrl: {
      type: String
    },
    value: {
      type: String
    },
    quillIndex: {
      type: Number,
      default: 0
    },
    toref: {
      type: String,
      default: 'quillEditor'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  components: {
    quillEditor
  },
  data() {
    return {
      content: '',
      editorOption: {
        placeholder: '',
        theme: 'snow', // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            // 点击按钮选择本地图片
            handlers: {
              image: value => {
                if (value) {
                  let index = this.quillIndex
                  // 触发input框选择图片文件
                  document.querySelectorAll('.quill-img input')[index].click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      }
    }
  },
  created() {
    this.content = this.value
  },
  watch: {
    value(n, o) {
      this.content = n
      // this.$refs[this.toref].quill.enable(false);//去掉焦点
      // // setTimeout(() => {
      // //   this.$refs[this.toref].quill.enable(true); //1秒之后可以点击（聚焦）
      // // }, 1000);
      //  this.$nextTick(()=>{
      //    this.$refs[this.toref].quill.enable(true)
      //  })
    }
  },
  methods: {
    beforeUpload() {},
    // 获得焦点事件
    onEditorFocus(event) {
      if (this.disabled) {
        event.enable(false)
      }
    },
    // 随机生成文件名
    random_string(len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    handleUploadForm(param) {
      let that = this

      let loading = that.$loading({
        lock: true,
        text: '上传中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      let formData = new FormData()
      formData.append('file', param.file)
      let config = {
        headers: {
          token: Vue.cookie.get('token'),
          'Content-Type': 'multipart/form-data'
        }
      }
      axios
        .post(
          `${this.$config.SERVER_URL}/admin/sys/oss/upload`,
          formData,
          config
        )
        .then(obj => {
          if (obj.status == 200) {
            let fileUrl = obj.data.data.url
            let quill = this.$refs[this.toref].quill
            let length = quill.getSelection().index // 获取光标所在位置

            quill.insertEmbed(length, 'image', fileUrl) // 插入资源  res.url为服务器返回的地址
            quill.setSelection(length + 1) // 调整光标到最后
          } else {
            this.$Message.error('图片插入失败')
          }
          loading.close()
        })

      // this.$post("file/upload", formData).then(res => {
      //   if (res.code === 0) { // 如果上传成功
      //     //let quill = this.$refs['myQuillEditor'].quill;// 获取富文本组件实例
      //     console.log(this.toref)
      //     let quill = this.$refs[this.toref].quill
      //     let length = quill.getSelection().index; // 获取光标所在位置

      //     quill.insertEmbed(length, "image", res.url); // 插入资源  res.url为服务器返回的地址
      //     quill.setSelection(length + 1); //调整光标到最后
      //   } else {
      //     this.$Message.error("图片插入失败");
      //   }

      //   loading.close()
      // })
    },
    uploadSuccess(res, file) {},
    getTxtchild() {
      this.$emit('getTxt', this.content)
    }
  }
}
</script>

<style scoped>
.quill-editor {
  line-height: normal;
}

.ivu-upload {
  display: none;
}

.el-upload-list,
ul {
  display: none !important;
}

em {
  font-style: italic !important;
}
</style>
